package com.ccteam.fluidmusic.ui

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.ui.SplashViewModel.Companion.MIN_WAIT_TIME
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 *
 * @author Xiaoc
 * @since 2021/1/7
 *
 * Logo显示页面
 */
@AndroidEntryPoint
class LogoFragment : Fragment() {

    private val splashViewModel by activityViewModels<SplashViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_logo, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        viewLifecycleOwner.lifecycleScope.launch {
            val shouldShowPermissionFragment = shouldShowPermissionFragment()
            splashViewModel.showPermissionFragment(shouldShowPermissionFragment)
            // 如果是没有获取基本权限，则进行对应权限界面的跳转
            if(shouldShowPermissionFragment){
                delay(MIN_WAIT_TIME)
                findNavController().navigate(LogoFragmentDirections.actionLogoFragmentToPermissionFragment())
            }
        }
    }

    /**
     * 检查是否进入APP时允许了基本权限
     * 基本权限目前包括存储权限
     * 如果允许返回 false 跳转到申请权限界面
     * 否则返回 true
     */
    private fun shouldShowPermissionFragment(): Boolean{
        return when(requireContext().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)){
            PackageManager.PERMISSION_DENIED -> {
                true
            }
            else ->{
                false
            }
        }
    }
}